import asyncio
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from asyncio import Queue
from share import watching_dicom_queue_dict


class MyHandler(FileSystemEventHandler):
    def __init__(self, on_create):
        self.create_cb = on_create
        pass

    def on_created(self, event):
        # 如果是文件被创建
        if event.is_directory:

            return
        self.create_cb(event.src_path)


class WatchingLoader:
    def __init__(self, watch_path, img_loader, client_id):
        from imgLoader.ImgLoader import ImgLoader
        self.client_id = client_id
        self.watch_path = watch_path  # 修改为你要监听的目录路径
        self.img_loader: ImgLoader = img_loader
        # 创建事件处理对象
        event_handler = MyHandler(self.on_create)

        # 创建观察者
        self.observer = Observer()
        self.observer.schedule(event_handler, self.watch_path, recursive=True)
        self.start()

    def start(self):
        self.observer.start()
        print('watching start')

    def stop(self):
        self.observer.stop()
        self.observer.join()
        print('watching stopped')

    def on_create(self, file_path):
        queue = watching_dicom_queue_dict.get(self.client_id)
        if queue is None:
            print(watching_dicom_queue_dict, self.client_id)
        queue.put(file_path)
